<template>
    <div class="w-[100%] fixed top-0 left-0 h-[100%] bg-black ">
        <el-amap ref="amapRef" :view-mode="useDataDashboardThemeStore.GET_SETTING('projectInfo')?.viewMode==1?'2D':'3D'" :pitch="20" :center="centerValue" :zoom="zoom"
            :style="`opacity: ${amapOpacity};`" @init="init" @complete="amapComplete" :doubleClickZoom="false">
            <el-amap-layer-image v-if="image" :url="image" :bounds="bounds" :opacity="1" :zIndex="100" />
            <el-amap-marker v-for="(marker, index) in  markers " :key="index" :position="marker.position"
                anchor="bottom-center">
                <div slot="content" class="cursor-default" @mouseenter="onMouseOver(marker)" >
                    <div class="relative   flex justify-center items-center flex-col"
                        v-if="marker.type == 'building'">
                        <!-- <div class="cursor-pointer z-1" @click="markerClick(marker)"
                            v-html="usePopup().createBuildingPopupContent(marker.alarmNum == 0 ? 'blue' : 'red', { buildingName: marker?.info?.buildingName })">
                        </div> -->
                        <div class="relative cursor-pointer z-1 top-[-37px] left-[9px] w-[60px] h-[60px]"
                            @click="markerClick(marker)"
                            v-html="getMarkerSvg(marker.type, marker, marker.alarmNum == 0 ? 'blue' : 'red', { buildingName: marker?.info?.buildingName })">
                        </div>

                    </div>
                    <div class="relative cursor-pointer  flex justify-center" v-else @click="markerClick(marker)">
                        <div class="top-[10px] w-[60px] h-[60px]"
                            v-html="getMarkerSvg(marker.type, marker, 'blue', {})"></div>
                    </div>
                </div>
            </el-amap-marker>
        </el-amap>
        <svg-colors />
    </div>
</template>

<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import SvgColors from "@/components/clickMap/svg-colors.vue"
import { projectpoint } from "@/api/screen/screenmune";
import { emitter } from '@/utils/mitt'
import {
    ElAmap,
    ElAmapPolygon,
    ElAmapMouseTool,
    ElAmapLayerImage,
    ElAmapMarker
} from "@vuemap/vue-amap";
import { useDataDashboardThemeStoreHook } from '@/store/modules/data-dashboard-theme'
import { getBuildingInfo, getDrawingInfo, getMonitorInfo, getFacilityInfo, getDeviceInfo, getDeviceBaseInfo } from "@/api/screen";
const useDataDashboardThemeStore = useDataDashboardThemeStoreHook()
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
const usePageVariablesStore = usePageVariablesStoreHook()
import { cloneDeep, isArray } from "@pureadmin/utils";
import { useMarker, iconType } from "@/components/clickMap/marker";
import { usePopup } from "@/components/clickMap/popup";
const emits = defineEmits(["amapLoaded"])
const defaultcenter = [103.981651, 30.722975];
const centerValue = ref(defaultcenter);
const isalrarmtype = ref(1)
const zoom = ref(12);
const createArea = ref(false);
const createType = ref("polygon");
const polygons = ref();
const channel = ref(null)
const image = ref(null)
const bounds = ref(null)
const markers = ref([
]);
const newdata = ref([])
const isEdit = ref(false);
const amapRef = ref();
const amapOpacity = ref(0)
const isalls = ref(0)
const props = defineProps({
    centerDialogVisible: {
        type: Boolean,
        default: false
    }
});
const footbtnid = ref(1)
const parms = ref(
    { menuType: 0, systematicId: "" }
)
onBeforeMount(() => {
    // getmarkimg()
    channel.value = new BroadcastChannel('data-dashboard-them');
    channel.value.onmessage = (e) => {
        parms.value.systematicId = ""
        useDataDashboardThemeStore.CHANGE_SETTING({ key: e.data.key, value: e.data.value })
        if (e.data.type == "getdataDashboardType") {
            if (e.data.value == 1) {
                let screen = cloneDeep(usePageVariablesStore.getScreen())
                screen.project = null
                usePageVariablesStore.setScreen(screen)
                isalrarmtype.value = 1
                getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'))
            } else {
                isalrarmtype.value = 1
                getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'))
            }
        } else if (e.data.type == "projectId") {
            let arr = markers.value.filter(item => item.id == e.data.value)
            //切换中心点位
            if (arr.length > 0) {
                centerValue.value = arr[0].position;
                map.value.setZoomAndCenter(18, centerValue.value);
                // map.value.setFitView();
            }
            channel.value.postMessage({ key: 'dataDashboardMenuId', value: e.data.value, type: 'changemenuTypemap' });
        } else if (e.data.type == "changemenuTypemap") {
            if (e.data.value || e.data.value == 0) {
                parms.value.menuType = e.data.value
                isalrarmtype.value = 1
                getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'))
            }
        } else if (e.data.type == "footbtnchange") {
            footbtnid.value = e.data.value
            if (e.data.value == 1) {
                isalrarmtype.value = 1
                getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'))
            } else {
                let arr = markers.value.filter(item => item.type == 1)
                if (arr.length > 0) {
                    markers.value = arr
                    nextTick(() => {
                        init(map.value)
                    })
                }
            }
        } else if (e.data.type == 'systematicId') {
            parms.value.systematicId = e.data.value
            isalrarmtype.value = 1
            getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'))
        } else if (e.data.type == "showverviewalrm") {
            isalrarmtype.value = e.data.value
            getmarkimg(e.data.value)
            isalls.value = e.data.value

        }
    }
    channel.value.postMessage({ key: 'getDataDashboardType', value: null, type: 'get' });
});
onBeforeUnmount(() => {
    channel.value.close()
})
const onclickmarker = (item) => {
    channel.value.postMessage({ key: '', value: cloneDeep(item), type: 'changeProject' });
    channel.value.postMessage({ key: 'dataDashboardType', value: 2, type: 'change' });
};
watch(
    () => props.centerDialogVisible,
    newVal => {
        if (newVal) {
            console.log(props.centerDialogVisible);
        }
    }
);
watch(
    () => useDataDashboardThemeStore.mapTheme,
    newVal => {
        if (newVal) {
            if (map.value) {
                const stynane = "amap://styles/" + newVal;   //自定义id  e9e8e6508afcdb45de31dd68cc1f500e
                map.value.setMapStyle(stynane);
                console.log('进来了stynane');

            }
        }
    }
);
const markerClick = (item: any) => {
    let items = JSON.parse(JSON.stringify(item))
    channel.value.postMessage({ key: 'mapmarkclick', value: items, type: 'mapmarkclick' });
};
// normal （标准）、dark（幻影黑）、light（ 月光银）、whitesmoke（远山黛）、fresh（草色青）、grey（雅士灰）、graffiti（涂鸦）、macaron（马卡龙）、blue（靛青蓝）、darkblue（极夜蓝）、wine（酱籽）
let map = ref(null);
const rightlog = ref([]);
const init = e => {
    map.value = e;
    const stynane = "amap://styles/" + useDataDashboardThemeStore.getMapTheme();
    map.value.setMapStyle(stynane);
    // map.value.setFeatures(['road', 'bg', 'building'])
    map.value.setFeatures(['road', 'bg', 'building', 'point'])
    map.value.zooms = [1, 20];
    setTimeout(() => {
        map.value.on('rotate', handleMapRotate);
        if (useDataDashboardThemeStore.dataDashboardButtonId == 2) {
            image.value = useDataDashboardThemeStore.GET_SETTING("projectInfo").projectPlan
            bounds.value = useDataDashboardThemeStore.GET_SETTING("projectInfo").bounds
        }
        map.value.setFitView();
    }, 500);
    //鼠标右键
};
function handleMapRotate() {
    console.log('地图旋转');

    const center = map.value.getCenter(); // 获取地图中心点经纬度
    map.value.setPosition(center); // 更新标记点位置
}
const amapComplete = () => {
    // amapOpacity.value = 1
    nextTick(() => {
        emits("amapLoaded");
    })
}
const onMouseOver = item => {
    // centerValue.value = item.position;
};
// 鼠标移出
const onMouseOut = (item) => {
    item.showdetals = false
};
const isalarem = (item) => {
    if (parms.value.menuType > 1) {
        return item.state.wait + item.state.dealing > 0 ? 1 : 2
    } else {
        return item.device.failure + item.device.offline + item.device.warning > 0 ? 1 : 2
    }
}
function getmarkimg(isred, type = 1) {
    newdata.value = []
    projectpoint().then(res => {
        if (res.code == 200) {
            res.result.building.forEach((item: any) => {
                if (item.markPoint.lat !== "" && item.markPoint.lng !== "") {
                    let dat = {
                        alarmNum: item.alarmNum,
                        isred: item.alarmNum == 0 ? 1 : 2,
                        position: [item.markPoint.lng, item.markPoint.lat],
                        type: 'building',
                        info: cloneDeep(item)
                    };
                    if (dat.isred == isred && isred == 2) {
                        newdata.value.push(dat)
                    } else if (isred == 1) {
                        newdata.value.push(dat)
                    }
                }
            });
            res.result.device.forEach((item: any) => {
                if (item.markPoint.lat !== "" && item.markPoint.lng !== "") {
                    let dat = {
                        commStatus: item.commStatus,
                        isred: item.commStatus == 1 ? 1 : 2,
                        position: [item.markPoint.lng, item.markPoint.lat],
                        type: 'device',
                        info: cloneDeep(item)
                    }
                    if (dat.isred == isred && isred == 2) {
                        newdata.value.push(dat)
                    } else if (isred == 1) {
                        newdata.value.push(dat)
                    }
                }
            });
            res.result.facilit.forEach((item: any) => {
                if (item.markPoint.lat !== "" && item.markPoint.lng !== "") {
                    let dat = {
                        status: istimes(item.expireDate, item.scrapDate),
                        isred: istimes(item.expireDate, item.scrapDate),
                        position: [item.markPoint.lng, item.markPoint.lat],
                        type: 'facilit',
                        info: cloneDeep(item)
                    }
                    if (dat.isred == 1 && isred == 2) {
                        newdata.value.push(dat)
                    } else if (isred == 1) {
                        console.log('进来了2');
                        newdata.value.push(dat)
                    }
                }
            });
            res.result.monitor.forEach((item: any) => {
                if (item.markPoint.lat !== "" && item.markPoint.lng !== "") {
                    let dat = {
                        position: [item.markPoint.lng, item.markPoint.lat],
                        isred: 1,
                        type: 'monitor',
                        info: cloneDeep(item)
                    };
                    if (dat.isred == isred && isred == 2) {
                        newdata.value.push(dat)
                    } else if (isred == 1) {
                        newdata.value.push(dat)
                    }
                }
            });

            if (JSON.stringify(markers.value) !== JSON.stringify(newdata.value) || markers.value.length == 0) {
                markers.value = newdata.value
            }
        }
    });
    if (type == 1) {
        nextTick(() => {
            init(map.value)
        })
    }
}

// 获取时间是否已过期
function istimes(oldtime, oldtime2) { //1 已过期 2 未过期
    let nows = new Date();
    let timeis = nows.getTime() - new Date(oldtime).getTime();
    let timeis1 = nows.getTime() - new Date(oldtime2).getTime();
    if (timeis > 0 || timeis1 > 0) {
        return 1;
    } else {
        return 2;
    }

}
let nows = new Date
const getMarkerSvg = (iconType, item, colorType, popupOptions) => {
    if (iconType === 'device') {
        let svg = useMarker().getSvgIcon(item.info.deviceIcon, 'device', item.commStatus == 1 ? 'blue' : 'red', popupOptions)
        return svg.svg
    } else if (iconType === 'building') {
        let svg = useMarker().getSvgIcon('', 'building', item.alarmNum == 0 ? 'blue' : 'red', popupOptions)
        return svg.svg
    } else if (iconType == 'facilit') {
        let svg = useMarker().getSvgIcon(item.info.facilitIcon, 'device', item.isred == 1 ? 'red' : 'blue', popupOptions)
        return svg.svg
    } else if (iconType == 'monitor') {
        let svg = useMarker().getSvgIcon('monitor', 'monitor', 'blue', popupOptions)
        return svg.svg
    }
    // let svg = useMarker().getSvgIcon('<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1721798655106" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5133" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M946.090667 818.978133L863.232 549.649067a150.2208 150.2208 0 0 0-143.496533-106.052267l-180.155734-0.1024v-112.4352a119.466667 119.466667 0 1 0-238.933333 0v174.045867a203.0592 203.0592 0 0 0-80.418133 162.56c0 111.4112 87.876267 201.710933 196.266666 201.710933 103.543467 0 188.16-82.466133 195.549867-186.965333h76.8c-7.5264 148.394667-126.6176 266.837333-272.349867 266.837333-150.562133 0-273.066667-126.327467-273.066666-281.6 0-79.496533 32.3072-151.1936 83.882666-202.427733a16.896 16.896 0 0 0 5.0688-11.9808v-45.943467c0-14.2336-16.605867-22.459733-27.648-13.482667-78.813867 64.085333-129.570133 162.9184-129.570133 273.834667 0 192.9216 153.122133 349.866667 341.333333 349.866667 183.3472 0 332.970667-149.060267 340.599467-335.104h4.078933l68.181334 176.964266a61.781333 61.781333 0 0 0 116.736-40.3968z" fill="#231815" p-id="5134"></path><path d="M419.345067 108.885333m-102.4 0a102.4 102.4 0 1 0 204.8 0 102.4 102.4 0 1 0-204.8 0Z" fill="#231815" p-id="5135"></path></svg>', 'device', 'red')
    // return svg.svg

}
const mesage = (data) => {
    getmarkimg(useDataDashboardThemeStore.GET_SETTING('showverviewalrm'), 2)
}
//消息推送

onMounted(() => {
    setTimeout(() => {
           if(useDataDashboardThemeStore.GET_SETTING('projectInfo')?.viewMode==2){
        map.value.viewMode="3D"
      }else{
        map.value.viewMode="2D"
      }
      if(useDataDashboardThemeStore.GET_SETTING('projectInfo')?.viewMode==2){
        map.value.setMapType("3D")
      }else{
        map.value.setMapType("2D")
      }
    }, 1000);
   
    emitter.on('alarmEventsProject', mesage)
})
onBeforeUnmount(() => {
    emitter.off('alarmEventsProject', mesage)
})

</script>

<style lang="scss" scoped>
.markcontent {
    width: 316px;
    padding: 0 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    height: 82px;
    background: linear-gradient(0deg, rgba(45, 21, 21, 0.54) 0%, rgba(87, 40, 47, 0.5) 70%, rgba(255, 93, 93, 0.42) 100%);
    border: 1px solid #D82B33;
    border-top: none;

    .linefeng {
        width: 1px;
        height: 45px;
        background: linear-gradient(0deg, rgba(12, 35, 72, 0.5) 0%, rgba(255, 255, 255, 0.5) 51%, rgba(12, 34, 70, 0.5) 100%);
        // opacity: 0.5;
    }

    .maplistitem {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .titleitem {
            font-size: 12px;
            line-height: 12px;
            margin-top: 10px;
            text-align: center;
        }

    }

}

.markcontents {
    width: 316px;
    padding: 0 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    height: 82px;
    background: linear-gradient(0deg, rgba(34, 43, 61, 0.5) 0%, rgba(26, 32, 61, 0.4) 51%, rgba(24, 41, 84, 0.4) 100%);
    border: 1px solid rgba(62, 108, 197, 0.93);
    border-top: none;

    .linefeng {
        width: 1px;
        height: 45px;
        background: linear-gradient(0deg, rgba(12, 35, 72, 0.5) 0%, rgba(255, 255, 255, 0.5) 51%, rgba(12, 34, 70, 0.5) 100%);
        // opacity: 0.5;
    }

    .maplistitem {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .titleitem {
            font-size: 12px;
            line-height: 12px;
            margin-top: 10px;
            text-align: center;
        }

    }

}

.markcontenta {
    width: 195px;
    padding: 0 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    height: 82px;
    background: linear-gradient(0deg, rgba(45, 21, 21, 0.54) 0%, rgba(87, 40, 47, 0.5) 70%, rgba(255, 93, 93, 0.42) 100%);
    border: 1px solid #D82B33;

    .linefeng {
        width: 1px;
        height: 45px;
        background: linear-gradient(0deg, rgba(12, 35, 72, 0.5) 0%, rgba(255, 255, 255, 0.5) 51%, rgba(12, 34, 70, 0.5) 100%);
        // opacity: 0.5;
    }

    .maplistitem {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .titleitem {
            font-size: 12px;
            line-height: 12px;
            margin-top: 10px;
            text-align: center;
        }

    }

}

.markcontentsa {
    width: 195px;
    padding: 0 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    height: 82px;
    background: linear-gradient(0deg, rgba(34, 43, 61, 0.5) 0%, rgba(26, 32, 61, 0.4) 51%, rgba(24, 41, 84, 0.4) 100%);
    border: 1px solid rgba(62, 108, 197, 0.93);

    .linefeng {
        width: 1px;
        height: 45px;
        background: linear-gradient(0deg, rgba(12, 35, 72, 0.5) 0%, rgba(255, 255, 255, 0.5) 51%, rgba(12, 34, 70, 0.5) 100%);
        // opacity: 0.5;
    }

    .maplistitem {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .titleitem {
            font-size: 12px;
            line-height: 12px;
            margin-top: 10px;
            text-align: center;
        }

    }

}

.marktitle {
    background: #532a2f;
    border: 1px solid #d82b33;
}

.marktitles {
    background: #0C285D;
    border: 1px solid #3E6CC5;
}

// 渐变文字
.gradient-text {
    background: linear-gradient(0deg, #6196ff 0%, #ffffff 100%);
    background-clip: text;
    -webkit-text-fill-color: transparent;
}

.titles {
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
}

.building {
    width: 157px;
    height: 30px;
    background: rgba(21, 48, 99, 0.8);
    border-radius: 4px;
    border: 1px solid #3E6CC5;
}
</style>
